import React, { useState, useEffect } from 'react';
import { List, Input, Picker, Form, Toast } from 'antd-mobile';
import { TextWidget, getMessage } from '@inbiz/react';
import { getToken } from '@inbiz/utils';
import { getUserInfo, setUserInfo as setUserInfoUtils } from '@inbiz/utils';
import { setUserInfo, GetUserInfoByToken } from '../service';
import Top from '../top';
import styles from './style.less';

const Item = List.Item;
interface Props {
  /**
   * 多语言
   */
  userInfo: {
    Name: string;
    Gender: number;
    Email: string;
    MainDepartmentName: string;
    Mobile: string;
    IdentityId: number;
  };
  pwdData: {
    length: number;
    enableEditUserInfo: boolean;
    enableEditPwd: boolean;
  };
  $userInfo: (arg: any) => void;
}

/**
 * BaseInfo 组件
 */
const BaseInfo = (props: Props) => {
  const [isEdit, $isEdit] = useState(false);
  const { userInfo, pwdData, $userInfo } = props;
  const [imageUrl, $imageUrl] = useState('');
  const [form] = Form.useForm();
  const { validateFields, getFieldsValue, setFieldsValue } = form;
  const token = getToken();
  const userInfoByToken = getUserInfo();

  useEffect(() => {
    if (userInfo) {
      $imageUrl(
        `${process.env.NODE_ENV == 'production' ? '' : InbizConfig.HOST
        }/Imagetype/GetUserAvatar?token=${token}&userId=${userInfo.IdentityId
        }&r=${Math.random()}`,
      );
    } else {
      $imageUrl('/resource/images/bpic24364.jpg');
    }
  }, [userInfo]);
  const modify = () => {
    validateFields()
      .then((res) => {
        const values = getFieldsValue();
        setUserInfo({
          ...values,
          genderMale: values.gender == getMessage('personalInfo.male') ? 1 : values.gender == getMessage('personalInfo.female') ? 2 : '',
        }).then((res) => {
          if (res.result == '0') {
            Toast.show({
              icon: 'success',
              content: `${getMessage('global.save')}${getMessage('personalInfo.success')}`,
            });
            setUserInfoUtils({
              ...userInfoByToken,
              userInfoByToken: {
                ...userInfoByToken.userInfoByToken,
                Name: values.realName,
                Gender: values.gender == '男' ? 1 : values.gender == '女' ? 2 : '',
                Mobile: values.mobile,
                Email: values.email
              }
            })
            GetUserInfoByToken({ token }).then((res: any) => {
              if (res.result == 0) {
                $userInfo(res.data);
                setUserInfoUtils({
                  ...userInfoByToken,
                  userInfoByToken: res.data
                })
                $isEdit(false);
              }
            })
          } else if (res.result == 225) {
            Toast.show({ icon: 'fail', content: getMessage('personalInfo.numberbeenUsed') });
          } else if (res.result == 221) {
            Toast.show({ icon: 'fail', content: getMessage('personalInfo.mailbeenUsed') });
          } else {
            Toast.show({ icon: 'fail', content: getMessage('personalInfo.editFailed') });
          }
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const changeIsEdit = () => {
    if (!pwdData.enableEditUserInfo) {
      return Toast.show({
        content: getMessage('personalInfo.notallowed'),
      });
    } else {
      $isEdit(true);
    }
  };
  return (
    <div className={styles.InbizInfomation}>
      <Top
        onClick={isEdit ? modify : changeIsEdit}
        title={getMessage('personalInfo.basicInfo')}
        operationTitle={isEdit ? getMessage('personalInfo.complete') : getMessage('global.edit')}
      />
      {!isEdit && (
        <List className={styles.baseInfoList}>
          {/* <Item extra={<img src={imageUrl} alt="" style={{ width: 18, height: 18 }} />}>
              头像
            </Item> */}
          <Item extra={userInfo?.Name}>
            <TextWidget>personalInfo.name</TextWidget>
          </Item>
          <Item
            extra={
              userInfo?.Gender == 1
                ? getMessage('personalInfo.male')
                : userInfo?.Gender == 2
                  ? getMessage('personalInfo.female')
                  : ''
            }
          >
            <TextWidget>personalInfo.gender</TextWidget>
          </Item>
          <Item extra={userInfo?.MainDepartmentName}>
            <TextWidget>personalInfo.department</TextWidget>
          </Item>
          <Item extra={userInfo?.Mobile}>
            <TextWidget>personalInfo.telephone</TextWidget>
          </Item>
          <Item extra={userInfo?.Email}>
            <TextWidget>personalInfo.email</TextWidget>
          </Item>
        </List>
      )}
      {isEdit && (
        <Form form={form} layout="horizontal" className={styles.eidtFormList}>
          <Form.Item
            name="realName"
            label={getMessage('personalInfo.name')}
            rules={[
              { required: true, message: getMessage('personalInfo.nameNotNull') },
              {
                pattern: /^[\u4e00-\u9fa5a-zA-Z\d——_]*$/,
                message: getMessage('personalInfo.nameTips'),
              },
            ]}
            initialValue={userInfo?.Name}
          >
            <Input maxLength={64} />
          </Form.Item>

          {/*document.activeElement.blur() 性别如果还有软键盘, 用这个试试*/}
          <Form.Item
            name="gender"
            label={getMessage('personalInfo.gender')}
            initialValue={
              userInfo?.Gender == 1
                ? getMessage('personalInfo.male')
                : userInfo?.Gender == 2
                  ? getMessage('personalInfo.female')
                  : ''
            }
            onClick={async () => {
              await Picker.prompt({
                columns: [
                  [
                    {
                      label: getMessage('personalInfo.male'),
                      value: '1',
                    },
                    {
                      label: getMessage('personalInfo.female'),
                      value: '2',
                    },
                  ],
                ],
                className: styles.genderPicker,
              }).then((res) => {
                if (res) {
                  setFieldsValue({
                    gender:
                      Number(res[0]) == 1
                        ? getMessage('personalInfo.male')
                        : Number(res[0]) == 2
                          ? getMessage('personalInfo.female')
                          : '',
                  });
                }
              });
            }}
          >
            <Input readOnly />
          </Form.Item>
          <Form.Item
            name="mobile"
            label={getMessage('personalInfo.telephone')}
            initialValue={userInfo?.Mobile}
            rules={[
              { pattern: /^[1]([3-9])[0-9]{9}$/, message: getMessage('personalInfo.telephoneTips') },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label={getMessage('personalInfo.email')}
            initialValue={userInfo?.Email}
            rules={[
              {
                type: 'email',
                message: getMessage('personalInfo.mailTips'),
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      )}
    </div>
  );
};

export default BaseInfo;
{
  /* <Item arrow="horizontal" extra={<PickImage userInfo={userInfo} />}>
                头像
              </Item>



        <Input
              {...getFieldProps('MainDepartmentName', { initialValue: userInfo.MainDepartmentName })}
            >
              部门
            </Input> */
}
